package com.guigu.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.MD5;
import com.guigu.common.utils.R;
import com.guigu.userservice.controller.BusinessmanEquipmentController;
import com.guigu.userservice.dto.Equipment;
import com.guigu.userservice.dto.Order;
import com.guigu.userservice.dto.PurchaseDemand;
import com.guigu.userservice.entity.BusinessmanEquipment;
import com.guigu.userservice.entity.Operator;
import com.guigu.userservice.entity.User;
import com.guigu.userservice.feign.MyOrderFeign;
import com.guigu.userservice.feign.myEquipmentFeign;
import com.guigu.userservice.mapper.UserMapper;
import com.guigu.userservice.service.UserService;
import com.guigu.userservice.vo.UserVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.guigu.common.utils.JwtUtils.getCourseUserJwtToken;

/**
 * <p>
 * 用户表（平台买卖双方用户） 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2025-09-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MyOrderFeign myOrderFeign;

    @Autowired
    private BusinessmanEquipmentController businessmanEquipmentController;

    @Override
    public PageInfo<User> queryUserByVo(UserVo vo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(vo.getSearchId() != null, "user_id", vo.getSearchId());
        queryWrapper.like(vo.getSearchUserName() != null, "user_name", vo.getSearchUserName());
        queryWrapper.like(vo.getSearchPhone() != null, "phone", vo.getSearchPhone());
        queryWrapper.ge(vo.getSearchMinTime() != null && !vo.getSearchMinTime().toString().isEmpty(), "register_time", vo.getSearchMinTime());
        queryWrapper.le(vo.getSearchMaxTime() != null && !vo.getSearchMaxTime().toString().isEmpty(), "register_time", vo.getSearchMaxTime());
        queryWrapper.ne(vo.getSearchType() != null, "user_type", vo.getSearchType());

        List<User> users = userMapper.selectList(queryWrapper);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @Override
    public R updateUserStatus(Integer id, Integer status) {
        User user = this.getById(id);
        if (user != null) {
            user.setStatus(status);
            this.updateById(user);
            return R.ok().message("更新成功");
        }
        return null;
    }

    @Override
    public R addUser(User user) {
//        修改用户启动状态
        user.setStatus(1);
//        默认注册为买家
        user.setUserType(0);
//        注册时间
        user.setRegisterTime(LocalDateTime.now());
//        创建时间
        user.setCreateTime(LocalDateTime.now());
//        更新时间
        user.setUpdateTime(LocalDateTime.now());
        this.save(user);
        return R.ok().message("添加成功");
    }

    @Override
    public R loginUser(String phone, String password) {
        // 1. 密码先加密
        password = MD5.encrypt(password);

        // 2. 查库
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = this.getOne(wrapper);

        // 3. 空值保护
        if (user == null) {
            return R.error().message("该手机号未注册");
        }

        // 4. 状态、密码校验
        if ("0".equals(user.getStatus())) {
            return R.error().message("用户被禁用");
        }
        if (!password.equals(user.getPassword())) {
            return R.error().message("用户名或密码错误");
        }

        return R.ok().message("登录成功").data("user", user);
    }

    @Override
    public R PCloginUser(User u) {
        u.setPassword(MD5.encrypt(u.getPassword()));
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",u.getPhone());

        User user= this.getOne(queryWrapper);
        if (user.getPhone() == null ) {
            return R.error().message("改手机号未注册");
        }
        if (user.getStatus().equals("0"))
            return R.error().message("用户被禁用");

        if (!user.getPassword().equals(u.getPassword())) {
            return R.error().message("用户名或密码错误");
        }

        String courseUserJwtToken = getCourseUserJwtToken(user.getUserId(),user.getUserName());

        return R.ok().data("courseUserJwtToken",courseUserJwtToken);
    }

    @Override
    public Integer sendCode() {

        //1.生成6位验证码
        Random random = new Random();
        //random.nextInt(900000) 意思会生成一个小于900000的数,无论生成多少在加上最后100000得到都是6位数
        Integer code = random.nextInt(900000) + 100000;

        return  code;
    }

    //根据业务员查询设备信息-》用设备id查询-》order-》/purchase_demand求购表的设备，
    // 再获取买家和卖家的信息，之后再去用户表获取数据
    @Override
    public List<User> getUniqueUserDetails(Long bid) {
        // 1. 查询设备信息（可能返回多个设备）
        List<BusinessmanEquipment> businessmanEquipmentList = businessmanEquipmentController.selectBusinessmanEquipmentList(Math.toIntExact(bid));

        // 空集合判断：如果没有设备，直接返回空列表
        if (businessmanEquipmentList == null || businessmanEquipmentList.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 收集所有设备关联的用户ID（全局Set，跨设备去重）
        Set<Long> userIds = new HashSet<>();

        // 遍历每个设备，收集对应的用户ID
        for (BusinessmanEquipment equipment : businessmanEquipmentList) {
            // 跳过空设备（避免空指针）
            if (equipment == null) {
                continue;
            }

            // 查询当前设备的订单信息
            Order order = myOrderFeign.queryOrderByEquipmentId3(
                    Long.valueOf(equipment.getEquipmentId())
            );
            // 查询当前设备的求购信息
            PurchaseDemand purchaseDemand = myOrderFeign.selectPurchaseByEId(
                    equipment.getBusinessmanId()
            );

            // 收集订单中的买家、卖家ID
            if (order != null) {
                if (order.getBuyerId() != null) {
                    userIds.add(order.getBuyerId());
                }
                if (order.getSellerId() != null) {
                    userIds.add(order.getSellerId());
                }
            }

            // 收集求购表中的用户ID（注意类型转换是否正确，避免NumberFormatException）
            if (purchaseDemand != null && purchaseDemand.getUserId() != null) {
                try {
                    userIds.add(Long.valueOf(purchaseDemand.getUserId()));
                } catch (NumberFormatException e) {
                    // 处理ID格式错误（例如非数字字符串）
                    log.error("求购表用户ID格式错误：{}", e);
                }
            }
        }

        // 3. 批量查询所有去重后的用户
        if (userIds.isEmpty()) {
            return Collections.emptyList();
        }

        return userMapper.selectBatchIds(userIds);

    }
}
